"""采购明细上加字段"""

from datetime import datetime, timedelta, date
from collections import defaultdict

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_compare
from odoo.addons import decimal_precision as dp

"""
采购要加：商品名称、商品编码，规格，生产厂家，单位，数量，含税单价，
价税合计，批号，生产日期，有效期，批准文号，备注"""


class PurchaseLine(models.Model):
    _inherit = 'purchase.order.line'

    user_id = fields.Many2one(related="order_id.user_id", store=True)
    add_lot_info = fields.Text('批号', compute="_compute_add_lot_info", store=True)
    add_approve_num = fields.Char('批准文号', compute="_compute_add_approve_num", store=True)
    nd_categ_id = fields.Many2one('product.category', related="product_id.categ_id",
                               store=True, string="分组")
    gsp_categ_id = fields.Many2one('gsp.product.categ', related="product_id.gsp_categ_id",
                                   store=True, string="分类")
    nd_poduct_name = fields.Char("产品名称", related="product_id.name", store=True)
    nd_default_code = fields.Char("产品编码", related="product_id.default_code", store=True)

    @api.depends('product_id')
    def _compute_add_approve_num(self):
        for line in self:
            if line.product_id.gsp_type == 'medicine':
                line.add_approve_num = line.product_id.approve_num
            elif line.product_id.gsp_type == 'instrument':
                line.add_approve_num = line.product_id.certificate_num.name

    @api.depends('move_ids.move_line_ids.lot_id',
                 'move_ids.move_line_ids.qty_done',
                 'move_ids.move_line_ids.lot_id.nd_production_date')
    def _compute_add_lot_info(self):
        for line in self:
            info = ''   # 批号，生产日期，有效期
            move_lines = line.move_ids.mapped('move_line_ids')
            # lot_ids = move_lines.mapped('lot_id')
            for move_line in move_lines:
                lot = move_line.lot_id
                if lot:
                    if lot.nd_production_date:
                        start = lot.nd_production_date.strftime('%Y年%m月%d日')
                    else:
                        start = ''
                    if lot.life_date:
                        end = lot.life_date.strftime('%Y年%m月%d日')
                    else:
                        end = ''
                    info += f'批号{lot.name}: {move_line.qty_done}{move_line.product_uom_id.name},{start}-{end}；\n'
            line.add_lot_info = info


class SaleLine(models.Model):
    _inherit = 'sale.order.line'

    nd_lot_info = fields.Text('批次信息', compute="_compute_nd_lot_info", store=True)
    nd_confirmation_date = fields.Datetime(related="order_id.confirmation_date", store=True, string="确认时间")
    nd_categ_id = fields.Many2one('product.category', related="product_id.categ_id",
                                  store=True, string="分组")
    gsp_categ_id = fields.Many2one('gsp.product.categ', related="product_id.gsp_categ_id",
                                   store=True, string="分类")
    nd_poduct_name = fields.Char("产品名称", related="product_id.name", store=True)
    nd_default_code = fields.Char("产品编码", related="product_id.default_code", store=True)
    nd_hospital_department = fields.Char('科室', related="order_id.nd_hospital_department", store=True)

    approve_date = fields.Date('批准日期', compute="_compute_approve_date", store=True)
    expire_date = fields.Date('有效期至', compute="_compute_approve_date", store=True)
    nd_register_num = fields.Many2one('gsp.certificate', string='注册证号或者备案凭证编号', related="product_id.certificate_num", store=True)
    nd_produce_permit_code = fields.Char('生产许可证号', related="nd_producer_id.permit_code", store=True)
    nd_produce_register_num = fields.Char('生产备案凭证编号', related="nd_producer_id.nd_produce_register_num", store=True)
    nd_purchase_approve_num = fields.Char('购货者经营许可证号', related="order_partner_id.nd_purchase_approve_num", store=True)
    nd_purchase_addr = fields.Char('购货者经营地址', related="order_partner_id.nd_purchase_addr", store=True)
    nd_purchase_contact = fields.Char('购货者联系方式', related="order_partner_id.nd_purchase_contact", store=True)

    @api.depends('nd_lot_lines.lot_id',
                 'nd_lot_lines.lot_id.nd_production_date',
                 'nd_lot_lines.lot_id.life_date')
    def _compute_approve_date(self):
        for line in self:
            if line.nd_lot_lines:
                lot_id = line.nd_lot_lines[0].lot_id
                if lot_id:
                    approve_date = expire_date = False
                    if lot_id.nd_production_date:
                        approve_date = fields.Datetime.context_timestamp(lot_id, lot_id.nd_production_date).date()
                    if lot_id.life_date:
                        expire_date = fields.Datetime.context_timestamp(lot_id, lot_id.life_date).date()
                    line.update({
                        'approve_date': approve_date,
                        'expire_date': expire_date,
                    })

    @api.depends('nd_lot_lines', 'nd_lot_lines.lot_id', 'nd_lot_lines.qty')
    def _compute_nd_lot_info(self):
        from_string = fields.Date.from_string
        for line in self:
            texts = []
            for lot in line.nd_lot_lines:
                text = ''
                if lot.lot_id:
                    text += f'{lot.lot_id.name}，{lot.qty};'
                    if lot.nd_production_date and lot.expire_date:
                        # text += f'{from_string(lot.nd_production_date)}至{from_string(lot.expire_date)}'
                        text += f'  效期{from_string(lot.expire_date)}'
                if text:
                    texts.append(text)
            line.nd_lot_info = '\n'.join(texts)

"""产品物料添加：物料明细表增加以下字段：
规格、注册证号或备案凭证号、单位、产品分组、产品分类、启用批号、启用效期、医疗器械分类、
是否冷链产品、存储条件、养护类别，近效期类别 、有效期"""

class Product(models.Model):
    _inherit = 'product.template'

    default_code = fields.Char(required=True, unique=True, track_visibility='onchange', string='产品编码')
    add_expire_info = fields.Char('启用效期', compute="_compute_add_expire_info", store=True)

    @api.depends('expire_manage', 'validity_date', 'validity_uom')
    def _compute_add_expire_info(self):
        uom = {'day': '天', 'month': '月', 'year': '年'}
        for product in self:
            if product.expire_manage:
                info = f'已启用-{product.validity_date}{uom.get(product.validity_uom, "")}'
            else:
                info = '未启用'
            product.add_expire_info = info


class report_account_coa(models.AbstractModel):
    _inherit = "account.coa.report"

    @api.model
    def _get_report_name(self):
        return "总分类账"

    def _get_columns_name(self, options):
        columns = [
            {'name': '', 'style': 'width:40%'},
            {'name': '借方', 'class': 'number'},
            {'name': '贷方', 'class': 'number', 'style': 'padding-right: 35px'},
        ]
        if options.get('comparison') and options['comparison'].get('periods'):
            columns += [
                {'name': '借方', 'class': 'number'},
                {'name': '贷方', 'class': 'number', 'style': 'padding-right: 35px'},
            ] * len(options['comparison']['periods'])
        return columns + [
            {'name': '借方', 'class': 'number'},
            {'name': '贷方', 'class': 'number', 'style': 'padding-right: 35px'},
            {'name': '借方', 'class': 'number'},
            {'name': '贷方', 'class': 'number'},
        ]


class MoveLine(models.Model):
    _inherit = 'account.move.line'

    acc_group_id = fields.Many2one('account.group', related="account_id.group_id", store=True)


class Picking(models.Model):
    _inherit = 'stock.picking'

    @api.multi
    def nd_print_picking(self):
        url = f'http://111.229.74.27:8080/webroot/decision/view/report?viewlet=nuoda%252Ftestchuku.cpt&dh={self.name}'
        return {
            'type': 'ir.actions.act_url',
            'target': 'new',
            'url': url,
        }


class Partner(models.Model):
    _inherit = 'res.partner'

    nd_purchase_addr = fields.Char('购货者经营地址')
    nd_purchase_contact = fields.Char('购货者联系方式')
    nd_purchase_approve_num = fields.Char('购货者经营许可证号')



